package com.ruoyi.system.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.dto.SpuCrumbDto;
import com.ruoyi.system.domain.vo.CategoryVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/system/crumb")
@Tag(name = "面包屑导航接口", description = "提供面包屑导航操作")
public class CrumbController {
    @Autowired
    private com.ruoyi.system.service.ICrumbService crumbService;

    /**
     * 根据categoryId获取面包屑导航
     */
    @Operation(summary = "根据categoryId获取面包屑导航", description = "")
    @GetMapping("/categoryId")
    public AjaxResult getCrumbByCategoryId(Long categoryId) {
        List<CategoryVo> list = crumbService.getCrumbByCategoryId(categoryId);
        if (list == null || list.isEmpty()) {
            return success();
        }
        // 转换为 [[name, id], ...] 的二维数组返回
        List<List<Object>> data = list.stream()
                .map(item -> java.util.Arrays.asList((Object) item.getName(), (Object) item.getId()))
                .collect(Collectors.toList());
        return success(data);
    }

    /**
     * 根据spuId获取面包屑导航
     */
    @Operation(summary = "根据spuId获取面包屑导航", description = "")
    @GetMapping("/spuId")
    public AjaxResult getCrumbBySpuId(Long spuId) {
        List<SpuCrumbDto> list = crumbService.getCrumbBySpuId(spuId);
        if (list == null || list.isEmpty()) {
            return success();
        }
        java.util.ArrayList<List<Object>> data = new java.util.ArrayList<>();
        // 仅添加一次 SPU 信息（过滤掉 null）
        list.stream()
                .filter(i -> i.getSpuId() != null && i.getSpuName() != null)
                .findFirst()
                .ifPresent(i -> data.add(java.util.Arrays.asList((Object) i.getSpuName(), (Object) i.getSpuId())));

        // 添加分类链，忽略空值
        data.addAll(list.stream()
                .filter(i -> i.getId() != null && i.getName() != null)
                .map(i -> java.util.Arrays.asList((Object) i.getName(), (Object) i.getId()))
                .collect(Collectors.toList()));
        return success(data);
    }

}
